<template>
  <div class="out">

    <p class="title">
      我的订单
      <el-select v-model="status" style="width: 100px" @change="changeStatus">
        <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
    </p>
    <span style="position: relative;left: 42%;font-size: 15px;color: red">
      温馨提示：已支付的订单可在电影放映前半小时退票
    </span>
    <hr style="width: 95%;height: 1px;border: none;background-color: #E5E5E5">

    <div class="item wow animate__bounceInLeft" v-for="(item,index) of orderList" :key="index">
      <p class="top">
        <span style="margin-right: 7%">
          下单日期:&nbsp;&nbsp;{{ item.buyTime }}
        </span>
        <span style="color: #999999">
          订单号:{{ item.number }}
        </span>

      </p>

      <div class="info">
        <img :src="`${$prefix}/${item.movie.mimg}`"
             @click="handleMovieDetail(item.movie)"
             :title="item.movie.mname"
             style="width: 66px;height: 90px;box-shadow: 0 2px 4px rgba(0, 0, 0, .18), 0 0 6px rgba(0, 0, 0, .08);cursor: pointer">
        <div style="width: 30%">
          <p style="font-size: 18px;margin: 3px 0">《{{ item.movie.mname }}》</p>
          <p class="not--name">{{ item.session.room }}</p>
          <p class="not--name"><span v-for="(seat,i) of item.seat.split(',')" :key="i"
                                     style="margin-right: 1.5%">{{
              Math.ceil(seat / 10)
            }}排{{ seat % 10 == 0 ? 10 : seat % 10 }}列</span></p>
          <p class="not--name" style="color: red">
            <span style="color: #999999">放映开始时间：</span>
            {{ item.session.begTime }}
          </p>
        </div>
        <div style="width: 25%;text-align: center;color: red;font-weight: 600">{{ item.total }}￥</div>
        <div style="width: 25%;text-align: center" v-show="status===2">
          <div>
            <p style="margin: 0;padding: 0;text-align: center">
              支付剩余时间
            </p>
            <p style="font-size: 25px;color: chocolate;margin: 0;padding: 0;text-align: center">
              {{ item.expireStr }}
            </p>
          </div>
        </div>
        <div style="width: 10%;text-align: center" v-show="status===2">
          <button type="primary" @click="handlePayOrder(item.number,item.total,index)" class="btn">支付</button>
        </div>
        <div style="width: 5%;text-align: center">
          <i class="el-icon-delete" @click="handleDelete(item.number)"></i>
        </div>
        <div style="width: 5%;text-align: center" v-if="returnTicketFlag(item.session.begTime)&&status===1">
          <button @click="returnTicket(item.number)" class="reback-buton">退款</button>
        </div>
      </div>
    </div>
    <el-pagination
        v-if="orderList.length>0"
        small
        layout="prev, pager, next"
        :page-size="page.pageSize"
        @current-change="handlePage"
        :total="total">
    </el-pagination>
    <el-empty description="暂无未支付订单，快去购票吧~~" v-show="orderList.length===0"></el-empty>
  </div>
</template>

<script>
import requests from "@/api/request";
import store from "@/store";

export default {
  name: "UserOrder",
  data() {
    return {
      options: [
        {
          key: 1,
          label: "已支付",
          value: 1
        },
        {
          key: 2,
          label: "未支付",
          value: 2
        },
        {
          key: 3,
          label: "已退款",
          value: 3
        }
      ],
      orderList: [],
      timer: null,
      status: 1,
      total: 0,
      page: {
        pageNo: 1,
        pageSize: 3
      },
    }
  },
  methods: {
    init() {//初始化获取订单数据
      requests({
        url: "/api/getTicketOrder",
        params: {
          uid: this.$store.state.user.uid,
          status: this.status,
          pageNo: this.page.pageNo,
          pageSize: this.page.pageSize
        },
        method: 'get'
      }).then(response => {
        this.orderList = response.data.records
        this.total = response.data.total
        this.orderList.forEach((item) => {
          const second = item.expireTime
          let h, m, s;
          h = Math.floor(second / (60 * 60))
          m = Math.floor((second - h * (60 * 60)) / 60)
          s = second - h * 60 * 60 - m * 60
          const expireStr = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s)
          item.expireStr = expireStr
        })
      }).catch(() => {
        this.$message.error("请求出错!")
      })
    },
    handlePage(newNo) {
      this.page.pageNo = newNo
      this.init()
    },
    handlePayOrder(number, total, index) {
      this.$confirm('是否确认支付该订单?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        requests({
          url: "/api/UpdateTicketStatus",
          params: {number: number, total: total, uid: this.$store.state.user.uid},
          method: 'post'
        }).then(response => {
          if (response.data.isSuccess) {
            this.$message.success("支付成功")
            this.orderList.splice(index, 1)
            requests({
              url: '/api/UpDateUserInfo',
              params: {uid: this.$store.state.user.uid},
              method: 'get'
            }).then(response => {
              this.$store.state.user = response.data
            })
          } else {
            this.$message.error(response.data.result)
          }
        })
      })
    },
    returnTicketFlag(time) {
      const inputDate = new Date(time);
      const halfHourAgo = new Date(inputDate.getTime() - 30 * 60 * 1000);//半小时前可退票
      const currentDate = new Date();
      return currentDate <= halfHourAgo;
    },
    handleDelete(number) {
      this.$confirm('是否确认取消并删除该订单?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        requests({
          url: '/api/HandleDeleteUserOrder',
          params: {number: number, status: this.status},
          method: 'post'
        }).then(() => {
          if (this.orderList.length <= 0) this.page.pageNo = 1
          this.init()
        }).catch(() => {
          this.$message.error("出错了,删除失败!")
        })
      })
    },
    handleMovieDetail(movie) {
      this.$store.state.movie = movie
      this.$router.push({name: 'MovieDetail'})
    },
    changeStatus() {
      this.init()
    },
    returnTicket(number) {
      this.$confirm('是否确认退款？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning'
      }).then(async () => {
        const promise = await this.$baseApi.callPostMethod(`returnTicket/${number}/${this.$store.state.user.uid}`);
        const data = promise.data
        if (data.code === 200) {
          this.$store.state.user = data.data
          this.init()
        }
      })
    }
  },
  created() {
    this.init()
  },
  watch: {
    status: {
      handler(newVal, oldVal) {
        if (newVal === 2) {
          this.timer = setInterval(() => {
            this.orderList.forEach((item, index) => {
              const second = item.expireTime
              if (second < 0) this.orderList.splice(index, 1)
              let h, m, s;
              h = Math.floor(second / (60 * 60))
              m = Math.floor((second - h * (60 * 60)) / 60)
              s = second - h * 60 * 60 - m * 60
              const expireStr = (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m) + ":" + (s < 10 ? "0" + s : s)
              item.expireTime -= 1
              item.expireStr = expireStr
            })
          }, 1000);
        } else {
          clearInterval(this.timer)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$wow.init()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  beforeRouteEnter(to, from, next) { //用于路由进去前判断是否进去，改函数在beforeCreate执行前执行，此时页面未创建，this指向为undefined
    if (JSON.stringify(store.state.user) == '{}') {
      next('/out')
    } else {
      next()
    }
  }
}
</script>

<style scoped>
.out {
  width: 55%;
  margin: 0 auto;
  margin-top: 30px;
  border: 1px solid #E5E5E5;

}

.title {
  margin-left: 2.5%;
  color: #ec443f;
  display: inline-block;
}

.item {
  width: 95%;
  margin: 0 auto;
  border: 1px solid #E5E5E5;
  margin: 20px auto;
}

.top {
  height: 50px;
  line-height: 50px;
  background-color: #f7f7f7;
  padding-left: 2.5%;
}

.info {
  width: 95%;
  margin: 0 auto;
  display: flex;
  /*定义子级元素垂直居中*/
  align-items: center;

}

.info div {
  display: inline-block;
}

.not--name {
  margin: 3% 0px 3% 6%;
  padding: 0px;
  font-size: 12px;
  color: #999999;
}

.btn {
  width: 70px;
  height: 30px;
  border: none;
  background-color: #df2d2d;
  border-radius: 18px;
  color: white;
  cursor: pointer;
}

i {
  font-size: 25px;
  cursor: pointer;
  color: red;
}

.reback-buton {
  background-color: #ff506a; /* 红色背景 */
  color: white; /* 白色文本 */
  padding: 5px 5px; /* 内边距 */
  border: none; /* 无边框 */
  border-radius: 5px; /* 圆角 */
  font-weight: bold; /* 加粗字体 */
  cursor: pointer; /* 鼠标悬停时变为指针 */
}
</style>